當我們有需求是多個 function 在執行前需要做檢查或者預先處理的時候,除了每次都在開頭複製一份一樣的程式碼以外,我們還有另外一種選擇 - Function Modifiers
昨天的合約:
function setName(string _name) public returns (string) {
/* Only owner has the permission to modify its name. */
if (msg.sender == owner) {
name = _name;
} else {
revert("Permission denied.");
}
return name;
}
抽出 funciton modifiter
之後,是不是看起來更直覺了呢?:
modifier onlyOwner() {
require(msg.sender == owner, "Permission denied.");
_;
}
function setName(string _name) public onlyOwner returns (string) {
/* Only owner has the permission to modify its name. */
name = _name;
return name;
}
最後的範例,有 parameters 的 modifier 用法:
pragma solidity ^0.4.25;
contract StateVariables {
string name;
uint public rename_counter;
address owner;
constructor() public {
/* Initailize default state. */
name = "unknown";
owner = msg.sender;
rename_counter = 0;
}
modifier checkOwner(address _addr) {
require(_addr == owner, "Address is not the owner.");
rename_counter += 1;
_;
}
function setName(string _name) public checkOwner(msg.sender) returns (string) {
name = _name;
return name;
}
function getName() public view returns (string) {
return name;
}
}
本日影片:
https://youtu.be/v1OEwKM1-Zg
Smart Contract 實戰教學播放清單:
https://www.youtube.com/playlist?list=PLHmOMPRfmOxSJcrlwyandWYiuP9ZAMYoF